package com.keur.money.ui.market.fm

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import com.keur.money.R
import com.keur.money.base.utils.thread.TimingThread
import com.keur.money.databinding.FmMullaPaymentProcessBinding
import com.keur.money.http.HttpHelper
import com.keur.money.mvp.ProFm
import com.keur.money.ui.market.act.KeurPaymentStatusAct
import com.keur.money.utils.event.KeurEventType
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/20 17:04
 * @Annotation：支付结果处理中
 */
class KeurPaymentProcessFm(): ProFm(), TimingThread.ITimingThreadListener {
    private var _binding: FmMullaPaymentProcessBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var orderData: JSONObject? = null
    var act: KeurPaymentStatusAct? = null

    //倒计时
    private var countdown = 30
    private var timeThread: TimingThread? = null

    constructor(act: KeurPaymentStatusAct, data: JSONObject): this(){
        this.act = act
        this.orderData = data
    }
    override fun getMullaRootView(inflater: LayoutInflater): View {
        _binding = FmMullaPaymentProcessBinding.inflate(inflater)
        return binding.root
    }

    override fun initMullaView() {
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTitleBarColor(Color.parseColor("#F8F8F8"))
        setMullaBackBtnRes(R.mipmap.mulla_back_black)
        setMullaTextTitle(getString(R.string.order_payment_status_title))
        setMullaRightBtnRes(R.mipmap.mulla_kefu_icon)
    }

    override fun initMullaListener() {
        //客服
        rootViewBinding.ivFun.setOnClickListener {
            act?.let {
                showMullaKefuDialog("PaymentProgress Page ${it.loadProductName()}",it.loadProductName(),it.loadProductToken())
                HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_CUSTOMER,"PaymentProgress Page ${it.loadProductName()}")
            }
        }
        //刷新
        _binding?.btnRefresh?.setOnClickListener {
            HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_PAYMENT_PROCESS_PAYMENT_UPDATE,"TransactionId：${orderData?.optString("transactionId")}")
            //再次调用查询状态接口
            act?.presenter?.loadMullaPaymentStatusAction()
        }
        //再次还款
        _binding?.btnPayment?.setOnClickListener {
            HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_PAYMENT_PROCESS_PAYMENT_AGAIN,"TransactionId：${orderData?.optString("transactionId")}")
            act?.presenter?.loadMullaPayLinkAction()
        }
    }

    override fun initMullaData() {
        if (orderData != null){
            onRefreshData(this.orderData)
        }

        //牌照信息
        val licenseInfo = KeurCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.visibility = View.GONE
        } else {
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.addView(licenseView())
            _binding?.licenseLayout?.visibility = View.VISIBLE
        }
    }

    /**
     * 刷新数据
     */
    private fun onRefreshData(data: JSONObject?){
        data?.let {
            this.orderData = it
            val realRepayAmount = it.optString("realRepayAmount","")
            _binding?.textAmount?.text = realRepayAmount
            _binding?.textName?.text = it.optString("product","")
            _binding?.textCreateTime?.text = it.optString("createTime","")

            _binding?.textTips?.text = String.format(getString(R.string.order_payment_status_processed_tips),realRepayAmount)

            countdown = 0
            showMullaPaymentStatus()
            //是否开启倒计时
            if (it.optBoolean("isStartCountdown",true)){
                startTimeThread()
            }
        }
    }

    /**
     * 启动倒计时
     */
    private fun startTimeThread() {
        if (timeThread != null) {
            timeThread?.stopThread()
        }
        countdown = 30
        showMullaPaymentStatus()
        if (timeThread == null) {
            timeThread = TimingThread()
            timeThread?.setThreadDelayMillis(1000)
            timeThread?.setLoadListener(this)
        }
        timeThread?.startThread()
    }

    /**
     * 倒计时
     */
    override fun onLoading() {
        if (countdown <= 0) {
            countdown = 30
            timeThread?.stopThread()

            //倒计时结束，自动调一次状态查询接口
            act?.presenter?.loadMullaPaymentStatusAction(false)
            return
        }
        countdown--
        showMullaPaymentStatus()
    }

    /**
     * 设置按钮状态
     */
    private fun showMullaPaymentStatus(){
        if (countdown <= 0){
            _binding?.btnPayment?.isEnabled = true
            _binding?.btnPayment?.isClickable = true
            _binding?.btnPayment?.text = String.format(getString(R.string.order_payment_status_make_payment_again),"")
        } else {
            _binding?.btnPayment?.isEnabled = false
            _binding?.btnPayment?.isClickable = false
            _binding?.btnPayment?.text = String.format(getString(R.string.order_payment_status_make_payment_again),"(${countdown}s)")
        }
    }

    override fun onStart() {
        super.onStart()
        act?.let {
            HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_REPAYMENT_PROCESS_START,it.loadProductName())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        act?.let {
            HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_REPAYMENT_PROCESS_END,it.loadProductName())
        }
        if (timeThread != null) {
            timeThread?.stopThread()
            timeThread = null
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}